<template>
  <view class="plate-modify-stats-container">
    <z-paging 
      ref="paging" 
      v-model="dataList" 
      @query="queryList"
      :auto="false"
      :refresher-enabled="true"
      :loading-more-enabled="true"
      :empty-view-text="'暂无数据'"
      class="list-paging"
    >
      <template #top>
        <!-- 页面标题 -->
        <view class="page-header">
          <view class="header-title">修改车牌统计</view>
        </view>
        
        <!-- 筛选区域 -->
        <view class="filter-section">
          <view class="filter-row">
            <view class="filter-item">
              <text class="filter-label">统计周期：</text>
              <picker mode="selector" :value="filters.periodIndex" :range="periodOptions" @change="onPeriodChange">
                <view class="date-picker">
                  <text>{{ filters.periodIndex >= 0 ? periodOptions[filters.periodIndex] : '请选择' }}</text>
                  <up-icon name="arrow-down" size="14"></up-icon>
                </view>
              </picker>
            </view>
            
            <view class="filter-item">
               <text class="filter-label">修改类型：</text>
               <picker :value="filters.modifyTypeIndex" :range="modifyTypes.map(item => item.name)" @change="onModifyTypeChange">
                  <view class="date-picker">
                   <text>{{ filters.modifyTypeIndex >= 0 ? modifyTypes[filters.modifyTypeIndex].name : '全部' }}</text>
                   <up-icon name="arrow-down" size="14"></up-icon>
                  </view>
              </picker>
            </view>
          </view>
          
          <view class="filter-actions">
            <button class="search-btn" @click="searchData">查询</button>
            <button class="reset-btn" @click="resetFilters">重置</button>
          </view>
        </view>
        
        <!-- 统计摘要 -->
        <view class="summary-section">
          <view class="summary-card">
            <view class="summary-title">挽回金额</view>
            <view class="summary-value">{{ summary.savedAmount }}</view>
          </view>
          <view class="summary-card">
            <view class="summary-title">损失金额</view>
            <view class="summary-value">{{ summary.lostAmount }}</view>
          </view>
          <view class="summary-card">
            <view class="summary-title">修改次数</view>
            <view class="summary-value">{{ summary.totalCount }}</view>
          </view>
        </view>
        
        <!-- 列表表头 -->
        <view class="list-header">
          <text class="list-cell">修改类型</text>
          <text class="list-cell">挽回金额</text>
          <text class="list-cell">损失金额</text>
          <text class="list-cell">修改次数</text>
        </view>
      </template>
      
      <!-- 列表内容 -->
      <view v-for="(item, index) in dataList" :key="index" class="list-row" @click="openDetail(item)">
        <view class="list-cell transaction-cell">
          <view class="transaction-tag modify-tag" :class="getTagClass(item.modifyTypeValue)">
            {{ item.modifyTypeName }}
          </view>
        </view>
        <text class="list-cell">{{ item.savedAmount }}元</text>
        <text class="list-cell">{{ item.lostAmount }}元</text>
        <text class="list-cell">{{ item.count }}次</text>
      </view>
    </z-paging>
    
    <!-- 详情弹窗 -->
    <view class="detail-modal" v-if="showDetailModal">
      <view class="detail-content">
        <view class="detail-header">
          <text class="detail-title">{{ currentDetail ? currentDetail.modifyTypeName + ' 详情' : '详情信息' }}</text>
          <text class="close-btn" @click="showDetailModal = false">×</text>
        </view>
        
        <view class="detail-body" v-if="currentDetail">
          <view class="detail-item">
            <text class="detail-label">修改类型：</text>
            <view class="detail-value">
              <view class="transaction-tag modify-tag" :class="getTagClass(currentDetail.modifyTypeValue)">
                {{ currentDetail.modifyTypeName }}
              </view>
            </view>
          </view>
          
          <view class="detail-item">
            <text class="detail-label">统计周期：</text>
            <text class="detail-value">{{ periodOptions[filters.periodIndex] }}</text>
          </view>
          
          <view class="detail-item">
            <text class="detail-label">挽回金额：</text>
            <text class="detail-value">{{ currentDetail.savedAmount }}元</text>
          </view>
          
          <view class="detail-item">
            <text class="detail-label">损失金额：</text>
            <text class="detail-value">{{ currentDetail.lostAmount }}元</text>
          </view>
          
          <view class="detail-item">
            <text class="detail-label">修改次数：</text>
            <text class="detail-value">{{ currentDetail.count }}次</text>
          </view>
          
          <view class="detail-item">
            <text class="detail-label">平均挽回金额：</text>
            <text class="detail-value">{{ currentDetail.avgSavedAmount }}元</text>
          </view>
          
          <view class="detail-item">
            <text class="detail-label">平均损失金额：</text>
            <text class="detail-value">{{ currentDetail.avgLostAmount }}元</text>
          </view>
          
          <view class="detail-item">
            <text class="detail-label">最高挽回金额：</text>
            <text class="detail-value">{{ currentDetail.maxSavedAmount }}元</text>
          </view>
          
          <view class="detail-item">
            <text class="detail-label">最高损失金额：</text>
            <text class="detail-value">{{ currentDetail.maxLostAmount }}元</text>
          </view>
          
          <view class="detail-item" v-if="currentDetail.timeDistribution && currentDetail.timeDistribution.length > 0">
            <text class="detail-label">时段分布：</text>
            <view class="detail-value">
              <view v-for="(time, idx) in currentDetail.timeDistribution" :key="idx" class="time-item">
                {{ time.name }}: {{ time.count }}次 ({{ time.percentage }}%)
              </view>
            </view>
          </view>
        </view>
      </view>
    </view>
  </view>
</template>

<script setup>
import { ref, reactive, onMounted, nextTick, computed } from 'vue'

// 筛选表单
const filters = reactive({
  periodIndex: 0,
  modifyTypeIndex: -1
})

// 统计周期选项
const periodOptions = [
  '日统计',
  '月统计',
  '年统计'
]

// 修改类型
const modifyTypes = [
  { name: '全部', value: 'all' },
  { name: '总体修改', value: 'total' },
  { name: '客服修改', value: 'customer_service' },
  { name: '巡检修改', value: 'inspector' }
]

// 列表数据
const dataList = ref([])
const paging = ref(null)

// 统计摘要数据
const summary = reactive({
  savedAmount: '0.00元',
  lostAmount: '0.00元',
  totalCount: '0次'
})

// 详情弹窗
const showDetailModal = ref(false)
const currentDetail = ref(null)

// 获取标签样式类
const getTagClass = (type) => {
  switch(type) {
    case 'total':
      return 'total-tag'
    case 'customer_service':
      return 'customer-tag'
    case 'inspector':
      return 'inspector-tag'
    default:
      return ''
  }
}

// 统计周期选择处理
const onPeriodChange = (e) => {
  filters.periodIndex = parseInt(e.detail.value)
}

// 修改类型选择处理
const onModifyTypeChange = (e) => {
  filters.modifyTypeIndex = parseInt(e.detail.value)
}

// 查询数据
const searchData = () => {
  if (paging.value) {
    paging.value.reload()
  }
}

// 重置筛选条件
const resetFilters = () => {
  filters.periodIndex = 0
  filters.modifyTypeIndex = -1
  
  nextTick(() => {
    if (paging.value) {
      paging.value.reload()
    }
  })
}

// 查询列表数据
const queryList = (pageNo, pageSize) => {
  // 模拟请求延迟
  setTimeout(() => {
    // 生成模拟数据
    const data = generateMockData(pageNo, pageSize)
    paging.value.complete(data)
    
    // 更新统计摘要
    updateSummary(data)
  }, 500)
}

// 更新统计摘要
const updateSummary = (data) => {
  // 计算总挽回金额、总损失金额和总次数
  let totalSavedAmount = 0
  let totalLostAmount = 0
  let totalCount = 0
  
  data.forEach(item => {
    totalSavedAmount += parseFloat(item.savedAmount)
    totalLostAmount += parseFloat(item.lostAmount)
    totalCount += item.count
  })
  
  // 更新摘要数据
  summary.savedAmount = totalSavedAmount.toFixed(2) + '元'
  summary.lostAmount = totalLostAmount.toFixed(2) + '元'
  summary.totalCount = totalCount + '次'
}

// 生成模拟数据
const generateMockData = (pageNo, pageSize) => {
  const data = []
  
  // 时段分布
  const timeDistributions = [
    { name: '早上(6:00-10:00)', value: 'morning' },
    { name: '中午(10:00-14:00)', value: 'noon' },
    { name: '下午(14:00-18:00)', value: 'afternoon' },
    { name: '晚上(18:00-22:00)', value: 'evening' },
    { name: '深夜(22:00-6:00)', value: 'night' }
  ]
  
  // 筛选修改类型
  let filteredModifyTypes = [...modifyTypes.slice(1)] // 排除'全部'选项
  if (filters.modifyTypeIndex > 0) { // 0是全部，大于0才需要筛选
    filteredModifyTypes = [modifyTypes[filters.modifyTypeIndex]]
  }
  
  // 计算总修改次数（用于计算占比）
  const totalModifyCount = Math.floor(Math.random() * 500) + 100 // 100-600次
  
  // 生成随机数据
  for (const modifyType of filteredModifyTypes) {
    // 根据修改类型设置不同的分布
    let countPercentage, savedAmountBase, lostAmountBase
    
    if (modifyType.value === 'total') {
      countPercentage = 1 // 100%
      savedAmountBase = Math.floor(Math.random() * 5000) + 10000 // 10000-15000元
      lostAmountBase = Math.floor(Math.random() * 3000) + 5000 // 5000-8000元
    } else if (modifyType.value === 'customer_service') {
      countPercentage = Math.random() * 0.2 + 0.6 // 60%-80%
      savedAmountBase = Math.floor(Math.random() * 4000) + 8000 // 8000-12000元
      lostAmountBase = Math.floor(Math.random() * 2000) + 3000 // 3000-5000元
    } else {
      countPercentage = Math.random() * 0.2 + 0.2 // 20%-40%
      savedAmountBase = Math.floor(Math.random() * 2000) + 2000 // 2000-4000元
      lostAmountBase = Math.floor(Math.random() * 1000) + 2000 // 2000-3000元
    }
    
    const count = Math.floor(totalModifyCount * countPercentage)
    const savedAmount = savedAmountBase
    const lostAmount = lostAmountBase
    
    // 生成时段分布
    const timeDistribution = []
    let remainingCount = count
    
    for (let i = 0; i < timeDistributions.length; i++) {
      const isLast = i === timeDistributions.length - 1
      const timeCount = isLast ? remainingCount : Math.floor(remainingCount * (Math.random() * 0.4 + 0.1)) // 10%-50%
      
      if (timeCount > 0) {
        const timePercentage = ((timeCount / count) * 100).toFixed(2)
        
        timeDistribution.push({
          name: timeDistributions[i].name,
          count: timeCount,
          percentage: timePercentage
        })
        
        remainingCount -= timeCount
      }
      
      if (remainingCount <= 0) break
    }
    
    // 添加数据
    data.push({
      modifyTypeName: modifyType.name,
      modifyTypeValue: modifyType.value,
      savedAmount: savedAmount.toFixed(2),
      lostAmount: lostAmount.toFixed(2),
      count,
      avgSavedAmount: (savedAmount / count).toFixed(2),
      avgLostAmount: (lostAmount / count).toFixed(2),
      maxSavedAmount: (savedAmount / count * (Math.random() * 0.5 + 1.5)).toFixed(2), // 平均值的1.5-2倍
      maxLostAmount: (lostAmount / count * (Math.random() * 0.5 + 1.5)).toFixed(2), // 平均值的1.5-2倍
      timeDistribution
    })
  }
  
  // 按修改次数排序
  return data.sort((a, b) => b.count - a.count)
}

// 打开详情弹窗
const openDetail = (item) => {
  currentDetail.value = item
  showDetailModal.value = true
}

// 页面加载时查询数据
onMounted(() => {
  searchData()
})
</script>

<style lang="scss" scoped>
.plate-modify-stats-container {
  min-height: 100vh;
  background-color: #f5f5f5;
}

.list-paging {
  height: 100%;
}

.page-header {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  padding: 40rpx 30rpx 30rpx;
  color: white;
  
  .header-title {
    font-size: 36rpx;
    font-weight: bold;
    text-align: center;
  }
}

.filter-section {
  background-color: white;
  padding: 20rpx 30rpx;
  margin-bottom: 20rpx;
  box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.05);
  
  .filter-row {
    display: flex;
    flex-wrap: wrap;
    margin-bottom: 20rpx;
  }
  
  .filter-item {
    flex: 1;
    min-width: 300rpx;
    margin-bottom: 10rpx;
    display: flex;
    align-items: center;
    
    .filter-label {
      font-size: 28rpx;
      color: #333;
      margin-right: 10rpx;
      white-space: nowrap;
    }
    
    .date-picker {
      flex: 1;
      height: 60rpx;
      border: 1px solid #ddd;
      border-radius: 6rpx;
      padding: 0 20rpx;
      display: flex;
      align-items: center;
      justify-content: space-between;
      font-size: 28rpx;
    }
  }
  
  .filter-actions {
    display: flex;
    justify-content: flex-end;
    gap: 20rpx;
    
    button {
      min-width: 160rpx;
      height: 70rpx;
      line-height: 70rpx;
      font-size: 28rpx;
      margin: 0;
      padding: 0 30rpx;
    }
    
    .search-btn {
      background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
      color: white;
    }
    
    .reset-btn {
      background-color: #f5f5f5;
      color: #666;
    }
  }
}

.summary-section {
  display: flex;
  justify-content: space-between;
  padding: 0 20rpx;
  margin-bottom: 20rpx;
  
  .summary-card {
    flex: 1;
    background-color: white;
    border-radius: 10rpx;
    padding: 20rpx;
    margin: 0 10rpx;
    box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.05);
    text-align: center;
    
    .summary-title {
      font-size: 24rpx;
      color: #666;
      margin-bottom: 10rpx;
    }
    
    .summary-value {
      font-size: 32rpx;
      color: #333;
      font-weight: bold;
    }
  }
}

.list-header {
  display: flex;
  background-color: #f8f8f8;
  padding: 20rpx 30rpx;
  font-size: 28rpx;
  color: #666;
  font-weight: bold;
  border-bottom: 1px solid #eee;
}

.list-row {
  display: flex;
  background-color: white;
  padding: 20rpx 30rpx;
  font-size: 28rpx;
  color: #333;
  border-bottom: 1px solid #f5f5f5;
}

.list-cell {
  flex: 1;
  display: flex;
  align-items: center;
}

.transaction-cell {
  display: flex;
  align-items: center;
}

.transaction-tag {
  padding: 6rpx 16rpx;
  border-radius: 6rpx;
  font-size: 24rpx;
  color: white;
}

.modify-tag {
  background-color: #4CAF50;
}

.total-tag {
  background-color: #4CAF50;
}

.customer-tag {
  background-color: #2196F3;
}

.inspector-tag {
  background-color: #FF9800;
}

.detail-modal {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.5);
  z-index: 999;
  display: flex;
  justify-content: center;
  align-items: center;
}

.detail-content {
  width: 80%;
  max-height: 80%;
  background-color: white;
  border-radius: 10rpx;
  overflow: hidden;
  display: flex;
  flex-direction: column;
}

.detail-header {
  padding: 30rpx;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
  display: flex;
  justify-content: space-between;
  align-items: center;
  
  .detail-title {
    font-size: 32rpx;
    font-weight: bold;
  }
  
  .close-btn {
    font-size: 40rpx;
    line-height: 1;
  }
}

.detail-body {
  padding: 30rpx;
  overflow-y: auto;
  flex: 1;
  
  .detail-item {
    margin-bottom: 20rpx;
    display: flex;
    
    .detail-label {
      width: 200rpx;
      font-size: 28rpx;
      color: #666;
    }
    
    .detail-value {
      flex: 1;
      font-size: 28rpx;
      color: #333;
    }
    
    .time-item {
      margin-bottom: 10rpx;
    }
  }
}
</style>